package com.sxt.provider.merchant.impl;

import com.sxt.commons.dto.ApiQueryOrderRequest;
import com.sxt.commons.typeEnum.OrderStateEnum;
import com.sxt.pojo.entity.Order;
import com.sxt.provider.cp.CpChannelService;
import com.sxt.provider.cp.CpService;
import com.sxt.provider.merchant.QueryOrderProviderService;
import com.sxt.provider.order.OrderService;
import com.sxt.provider.sp.SpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

@Service("queryOrderProvider")
public class QueryOrderProviderServiceImpl implements QueryOrderProviderService {
	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${api.response.sign.name}")
	String apiResponseSignName;
	@Value("${api.response.key.name}")
	String apiResponseKeyName;

	@Autowired
	OrderService orderService;
	@Autowired
	CpChannelService cpChannelService;
	@Autowired
	SpService spService;
	@Autowired
	CpService cpService;

	@Override
	public Map<String, Object> queryOrder(ApiQueryOrderRequest request) throws Exception {
		Assert.notNull(request, "请求错误");
		Assert.notNull(request.getMchId(), "缺少mchId参数");
		Assert.notNull(request.getOutTradeNo(), "缺少outTradeNo参数");
		Order order = orderService.getByCpidAndOutTradeNo(Long.valueOf(request.getMchId()),request.getOutTradeNo());
		Assert.notNull(order, "未查询到该订单");

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("outTradeNo",order.getOutTradeNo());
		resultMap.put("tradeNo",order.getTradeNo());
		resultMap.put("totalFee",order.getAmount());
		resultMap.put("type",order.getChannelType());
		resultMap.put("state",dealState(order));//（0：交易成功；1：交易失败；2交易处理中；）
		resultMap.put("mch_rate",order.getFeeRecharge());

		return resultMap;
	}

	/**
	 * 处理交易状态
	 * @param order
	 * @return
	 */
	private String dealState(Order order){
		if(order.getState()== OrderStateEnum.SUCCESS.getType())return"0";
		else if (order.getState()==OrderStateEnum.REQERROR.getType()
				||order.getState()==OrderStateEnum.PAYERROR.getType()
				||order.getState()==OrderStateEnum.CLOSE.getType())return"1";
		else{
			return"2";
		}
	}
}
